/**
 * Copyright (C) 2009-2012, KingHool.com
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program. If not, see http://www.gnu.org/licenses.
 */
package com.kinghool.smodel.io.bean;

import java.lang.reflect.Constructor;

import com.kinghool.ebos.commons.Platform;

/**
 * 
 * @Author Allen Deng(dengtailin@gmail.com) 
 */
public class DefaultBeanFactory implements IBeanFactory {

	private Constructor<?> constructor;
	private Class<?> clazz;
	
	public DefaultBeanFactory(Class<?> clazz) {
		boolean initialized = false;
		if (clazz != null) {
			try {
				Constructor<?> constructor = clazz.getDeclaredConstructor();
				if (constructor != null) {
					constructor.setAccessible(true);
					this.constructor = constructor;
					this.clazz = clazz;
					initialized = true;
				}
			} catch (Exception e) {//ignore
			}
		}
		if (!initialized) {
			throw new IllegalArgumentException("Illegal argument clazz, it does not has default constructor:" + clazz);
		}
	}
	 
	public Object newBean() {
		try {
			return constructor.newInstance();
		} catch (Exception e) {
			Platform.getLogManager().error("Fail to create bean " + clazz.getName(), e, this);
		} 
		return null;
	}

	public String getClassName() {
		return clazz.getName();
	}
}
